package credential

import (
	"fmt"
	"kubeInstall/pkg/client/db"
	"kubeInstall/server/models/cluster"
	"kubeInstall/utils/uuid"
)

func ListCredentials(limit, Offset int) ([]*cluster.Credential, error) {
	var cred []*cluster.Credential
	if limit == 0 {
		limit = 10
	}

	err := db.Db.Select("*").Limit(limit).Offset((Offset - 1) * limit).Find(&cred).Error
	if err != nil && err != db.ErrRecordNotFound {
		return nil, err
	}

	return cred, nil
}

func CheckCredentialIdIsValid(CredentialId string) bool {
	var count int

	db.Db.Model(cluster.Credential{}).Where("credential_id = ?", CredentialId).Count(&count)
	if count > 0 {
		return true
	}

	return false
}

func GetCredential(credentialId string) (cluster.Credential, error) {
	var credData cluster.Credential
	err := db.Db.Where("credential_id = ?", credentialId).First(&credData).Error

	if err != nil {
		if err == db.ErrRecordNotFound {
			return credData, fmt.Errorf("credential ID %s not found", credentialId)
		}
		return credData, err
	}

	return credData, nil
}

func AddCredential(cred *cluster.Credential) (*cluster.Credential, error) {
	var count int

	db.Db.Model(cluster.Credential{}).Where("name = ?", cred.Name).Count(&count)
	if count > 0 {
		return nil, fmt.Errorf(" Credential Name: %s already exsist", cred.Name)
	}

	cred.ID = uuid.GenUUID()

	if err := db.Db.Create(&cred).Error; err != nil {
		return nil, err
	}
	return cred, nil

}

func DeleteCredential(credentialId string) error {
	if err := db.Db.Delete(cluster.Credential{ID: credentialId}).Error; err != nil {
		return err
	}
	return nil
}

func UpdateCredential(credentialId string, cred *cluster.Credential) error {

	if err := db.Db.Model(&cluster.Credential{}).Where("credential_id = ?", credentialId).Update(&cred).Error; err != nil {
		return err
	}

	return nil
}
